package jmu.cyxwcy.librarymanagement.interceptors;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jmu.cyxwcy.librarymanagement.utils.JwtUtil;
import jmu.cyxwcy.librarymanagement.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//登录拦截器
@Component//非con,service,mapper使用该注释，加入IOC容器
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证，获取请求头需要前端代码，没有可以先用apipost
        //request，所有的请求对象都在这里面
        String token = request.getHeader("Authorization");
        try {
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);//这里的token是键,查找redis中的值是否存在
            if(redisToken==null){
                //没有查找到，也可能是失效
                throw new RuntimeException();
            }
            //解析的过程中已经进行了验证，如果验证成功就不会出现异常，所以要用try,catch包起来
            Map<String, Object> claims = JwtUtil.parseToken(token);
//            把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
//            放行
            return true;
        } catch (Exception e) {
            //设置http响应状态码为401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空Threadlocal中的数据
        ThreadLocalUtil.remove();
    }
}
